<template>
  <div style="height: 100%;">
    <!--菜单区域-->
    <div class="sidebar-container">
      <div style="height: 50px;text-align: center">
        <img
          v-show="isCollapse"
          style="height: 40px;width: 40px;vertical-align: middle;"
          src="/static/img/logo.png">
        <span class="login-text" v-show="!isCollapse">esionet-admin</span>
      </div>
      <div class="el-scrollbar">
        <div class="scrollbar-wrapper el-scrollbar__wrap" style="margin-bottom: -18px; ">
          <div class="el-scrollbar__view">
            <el-menu
              @select="menuChange"
              router
              class="el-menu-vertical"
              :collapse="isCollapse"
              unique-opened
              :default-active="$route.path"
              background-color="#304156"
              text-color="rgb(191, 203, 217)"
              active-text-color="#1890ff"
            >
              <nav-menus :menu-list="menuList"></nav-menus>
            </el-menu>
          </div>
        </div>
      </div>
    </div>
    <!--内容区域-->
    <div class="main-container hasTagsView" :isCollapse="isCollapse">
      <div class="navbar">
        <!--菜单收起-->
        <div class="el-breadcrumb app-breadcrumb breadcrumb-container">
          <el-tooltip class="item" effect="dark" content="收起菜单" placement="bottom">
                        <span @click="sideEdge" v-show="!isCollapse"
                              class="el-breadcrumb__item side-edge iconfont iconcebianlanshousuo"></span>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="展开菜单" placement="bottom">
                        <span @click="sideEdge" v-show="isCollapse"
                              class="el-breadcrumb__item side-edge iconfont iconcebianlandanchu"></span>
          </el-tooltip>
        </div>
        <!--菜单模块-->
        <!--面包屑-->
        <div class="menu-breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <template v-for="item in breadcrumbs">
              <el-breadcrumb-item>{{ item.meta.title}}</el-breadcrumb-item>
            </template>
          </el-breadcrumb>
        </div>
        <!--右侧菜单-->
        <div class="right-menu">

          <el-tooltip class="item" effect="dark" content="关注公众号" placement="bottom">
            <div class="right-menu-item hover-effect" @click="dialogVisible=true">
              <span class="el-icon-warning-outline">公众号</span>
            </div>
          </el-tooltip>


          <el-tooltip v-show="!fullScreen" class="item" effect="dark" content="全屏" placement="bottom">
            <div class="right-menu-item hover-effect" @click="handleFullScreen()">
              <span class="iconfont iconquanping"></span>
            </div>
          </el-tooltip>

          <el-tooltip v-show="fullScreen" class="item" effect="dark" content="退出全屏" placement="bottom">
            <div class="right-menu-item hover-effect" @click="handleFullScreen()">
              <span class="iconfont icontuichuquanping"></span>
            </div>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="刷新缓存" placement="bottom">
            <div class="right-menu-item hover-effect" @click="handleRefreshCache()">
              <span class="iconfont iconshuaxin"></span>
            </div>
          </el-tooltip>
          <div class="right-menu-item hover-effect">
            <i class="el-icon-bell"></i>
            <el-badge :value="200" :max="99" class="item"></el-badge>
          </div>
          <div class="right-menu-item hover-effect avatar-container">
            <el-dropdown @command="menuCommand">
              <div class="avatar-wrapper">
                <img src="../assets/img/head.jpg"
                     class="user-avatar">
                <i class="el-icon-caret-bottom nav-user-more"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item style="text-align: center">{{user.username}}</el-dropdown-item>
                <el-dropdown-item command="userInfo" divided icon="iconfont icongerenxinxi">
                  <router-link tag="span" to="/sys/user/userInfo">个人信息</router-link>
                </el-dropdown-item>
                <el-dropdown-item command="password" icon="iconfont iconmima">修改密码</el-dropdown-item>
                <el-dropdown-item command="logout" divided icon="iconfont icontuichu">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <div id="tags-view-container" class="tags-view-container">
        <!--右键菜单-->
        <ul v-show="showCM" class="contextmenu" :style="cmStyle">
          <router-link tag="span" :to="cmObj.route">
            <li @click="refresh">刷新</li>
          </router-link>
          <li @click="isLock(false)" v-if="!cmObj.isLock">锁定</li>
          <li @click="isLock(true)" v-if="cmObj.isLock">解锁</li>
          <li @click="closeOther">关闭其他</li>
          <li @click="closeAll">关闭所有</li>
        </ul>
        <!--左移按钮-->
        <div class="btn-con left-btn" @click="handleTabLeft()">
                    <span type="button" class="tags-btn-text"><span>
                        <i class="el-icon-arrow-left" style="font-size: 18px;"></i></span>
                    </span>
        </div>

        <!--tabs列表-->
        <div class="scroll-outer" @mousewheel="handleTabWheel">
          <div class="scroll-body" :style="tabLeft">
            <router-link v-for="item in tabs" tag="span" :to="item.route" :key="item.route"
                         class="tab-tag tab-tag-primary tab-tag-dot"
                         :class="item.route === $route.path ? 'tab-tag-checked':''"
                         :ref="item.route === $route.path ? 'tabCheck':''"
                         :data-route="item.route">
              <div @click="tabChange(item.route)" @contextmenu.prevent="tabContextMenu(item.route)">
                <span v-if="item.isLock === false" class="iconfont iconyk_yuanquan_fill "></span>
                <span v-if="item.isLock === true" class="iconfont iconziyuanxhdpi lock"></span>
                <span class="tab-tag-text">{{item.title}}</span>
                <i v-if="!item.isHome && !item.isLock " class="el-icon-close"
                   @click.stop="closeTab(item.route)"></i>
              </div>
            </router-link>
          </div>
        </div>
        <!--右移按钮-->
        <div class="btn-con right-btn" @click="handleTabRight()">
                    <span type="button" class="tags-btn-text"><span>
                        <i class="el-icon-arrow-right" style="font-size: 18px;"></i></span>
                    </span>
        </div>
        <!--更多按钮-->
        <div class="btn-con tabs-more-btn">
          <el-dropdown @command="tabCommand">
                    <span type="button" class="tags-btn-text"><span>
                        <i class="iconfont iconguanbi"></i></span>
                    </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="closeOther">关闭其他</el-dropdown-item>
              <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <section class="app-main">
        <div class="app-container">
          <router-view></router-view>
        </div>
      </section>
    </div>

    <!--todo 关注公众号-->
    <el-dialog
      title="关注公众号-了解项目最新动态"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :show-close="false"
      width="400px">
      <img src="/static/img/esionet.jpg">
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">不关注</el-button>
          <el-button type="primary" @click="confirmFollow">已关注</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import waterMark from '@/assets/js/watermark'
  import {getCookie} from '@/libs/cookie'
  import {getUserMenu} from '@/api/sys/menuApi'

  export default {
    name: 'App',
    data() {
      return {
        dialogVisible: true,
        breadcrumbs: [],
        subMenu: {},//暂存当前展开的菜单以及子菜单
        user: {headPic: '', username: 'chenyi'},
        tabs: {'/home': {route: '/home', title: '首页', url: '/home', isHome: true, isLock: false}},
        tabCheck: '/home',//当前选中的tab路由
        isCollapse: false,//左侧菜单时候收缩
        menuList: [],//菜单列表
        menuMap: {},//菜单map
        tabLeft: {//tab样式
          left: '0px'
        },
        cmStyle: {//菜单样式
          left: '0px',
          top: '26px'
        },
        showCM: false,//是否显示右键菜单
        cmObj: {route: '/home'},//当前右键tab对象
        cmCheck: '',//当前右键tab路由地址,
        loading: true,
        fullScreen: false,//是否全屏
      }
    },
    watch: {
      $route(to, from) {
        let currentPath = to.path.replace('/redirect', '')
        this.getBreadcrumb()
        if (!this.tabs[currentPath]) {
          if ('/' === currentPath) {
            this.$router.push({path: '/home'})
            return
          }
          let currentMenu = this.menuMap[currentPath]
          console.log(currentMenu)
          this.tabs[currentPath] = {
            route: currentMenu.route,
            title: currentMenu.name,
            url: currentMenu.url,
            isHome: false,
            isLock: false
          }
        }
        this.$nextTick(function () {
          let currentPath = to.path.replace('/redirect', '')
          if (currentPath === '/home') {
            this.tabLeft = {left: '0px'}
            return
          }
          let currentTabLeft = document.querySelector('.scroll-body [data-route=\'' + currentPath + '\']').offsetLeft
          let scrollOuterWidth = document.querySelector('.scroll-outer').offsetWidth
          let scrollBodyWidth = document.querySelector('.scroll-body').offsetWidth
          this.tabLeft = {left: '0px'}
          if (scrollBodyWidth < scrollOuterWidth) {
            return
          }
          if (currentTabLeft > scrollOuterWidth / 2) {
            if (scrollOuterWidth / 2 - currentTabLeft + scrollBodyWidth + 10 <= scrollOuterWidth) {
              this.tabLeft = {left: scrollOuterWidth - scrollBodyWidth - 10 + 'px'}
              return
            }
            this.tabLeft = {left: (scrollOuterWidth / 2 - currentTabLeft) + 'px'}
          }
        })
      },
      tabs(val, oldVal) {
        //tabs值改变时，页面渲染完后的回调
        this.$nextTick(function () {
          let scrollBodyWidth = document.getElementsByClassName('scroll-body')[0].offsetWidth
          let scrollOuterWidth = document.getElementsByClassName('scroll-outer')[0].offsetWidth
          if (scrollBodyWidth > scrollOuterWidth) {
            this.tabLeft = {left: (scrollOuterWidth - scrollBodyWidth - 10) + 'px'}
          } else {
            this.tabLeft = {left: '0px'}
          }
        })
      }
    },
    created: function () {
      this.getBreadcrumb()
      let _this = this
      let fullScreen = _this.fullScreen
      document.onkeydown = function (e) {
        let key = window.event.keyCode
        if (key === 122) {
          _this.fullScreen = !fullScreen
        }
      }
    },
    mounted: function () {
      let _this = this
      //获取菜单列表
      getUserMenu({}).then(res => {
        if (res.code === 200) {
          //是否有锁定的tab
          let lockTabs = _this.$t.getLocalStorageItem('lockTabs') || {}
          if (lockTabs) {
            for (let key in lockTabs) {
              _this.tabs[key] = lockTabs[key]
            }
          }
          _this.menuList = res.data;
          _this.setMenuMap(res.data)
          //路由回填
          if (_this.$route.path !== '/home' && _this.$route.path !== '/') {
            let item = _this.menuMap[_this.$route.path]
            if (!lockTabs[item.route]) {
              _this.tabs[item.route] = {
                route: item.route,
                title: item.name,
                url: item.url,
                isHome: false,
                isLock: false
              }
            }
            _this.cmObj = {
              route: item.route,
              title: item.name,
              url: item.url,
              isHome: false,
              isLock: false
            }
            _this.tabCheck = item.route
          }
        } else {
          _this.$message.error(res.msg)
        }
      })
      if (_this.$route.path === '/') {
        _this.tabCheck = '/home'
        _this.$router.push({path: '/home',})
      }
      //添加水印
      waterMark.set(getCookie('user'))
    },
    methods: {
      confirmFollow() {
        let _this = this;
        _this.$confirm('真的关注了吗？', '提示', {
          confirmButtonText: '真的关注了',
          cancelButtonText: '还没，马上关注',
          type: 'warning',
          callback: function (action, instance) {
            if (action === "confirm") {
              _this.dialogVisible = false;
            }
          }
        });
      },
      //菜单对象转map
      setMenuMap: function (data) {
        let _this = this
        //保存map数据
        for (let i = 0; i < data.length; i++) {
          _this.menuMap[data[i].route] = data[i]
          data[i].children && _this.setMenuMap(data[i].children)
        }
      },
      //点击菜单
      menuChange: function (path, routes) {
        if (path === this.$route.path) {
          return false
        }
        let _this = this
        let item = _this.menuMap[path]
        if (path !== _this.tabCheck) {
          _this.tabCheck = path
        }
        //该菜单已存在
        if (_this.tabs[path]) {
          return false
        }

        _this.tabs[item.route] = {
          route: item.route,
          title: item.name,
          url: item.url,
          isHome: false,
          isLock: false
        }
      },
      //点击tab
      tabChange: function (path) {

        this.showCM = false
        if (path !== this.tabCheck) {
          this.tabCheck = path
        }
      },
      //关闭标签
      closeTab: function (path) {
        let _this = this
        this.$delete(this.tabs, path)
        if (path === this.tabCheck) {
          _this.tabCheck = '/home'
          _this.$router.push({path: '/home',})
        }
      },
      // 侧边栏是否收缩
      sideEdge: function () {
        this.isCollapse = !this.isCollapse
      },
      //tab左移
      handleTabLeft: function () {
        let scrollBodyWidth = document.getElementsByClassName('scroll-body')[0].offsetWidth
        let scrollOuterWidth = document.getElementsByClassName('scroll-outer')[0].offsetWidth
        if (scrollBodyWidth < scrollOuterWidth) {
          return
        }
        let tabLeftPX = this.tabLeft.left.replace('px', '')
        let resPX = parseInt(tabLeftPX)
        if (resPX + scrollBodyWidth - 230 <= scrollOuterWidth) {
          this.tabLeft = {left: scrollOuterWidth - scrollBodyWidth - 10 + 'px'}
          return
        }
        this.tabLeft = {left: (resPX - 240) + 'px'}
      },
      //tab右移
      handleTabRight: function () {
        let scrollBodyWidth = document.getElementsByClassName('scroll-body')[0].offsetWidth
        let scrollOuterWidth = document.getElementsByClassName('scroll-outer')[0].offsetWidth
        if (scrollBodyWidth < scrollOuterWidth) {
          return
        }
        let tabLeftPX = this.tabLeft.left.replace('px', '')
        let resPX = parseInt(tabLeftPX) + 240
        if (resPX > 0) {
          this.tabLeft = {left: '0px'}
          return
        }
        this.tabLeft = {left: (resPX) + 'px'}
      },
      //tab右键监听
      tabContextMenu: function (path) {
        let _this = this
        if (path === '/home') {
          return
        }
        let tabLeftPX = this.tabLeft.left.replace('px', '')
        let left = document.querySelector('.scroll-body [data-route=\'' + path + '\']').offsetLeft + parseInt(tabLeftPX)
        let currentWidth = document.querySelector('.scroll-body [data-route=\'' + path + '\']').offsetWidth
        this.cmStyle.left = left + (currentWidth) + 'px'
        this.showCM = true
        _this.cmObj = _this.tabs[path]
      },
      //下拉菜单事件监听
      menuCommand: function (type) {
        let _this = this
        if (type === 'logout') {
          // window.location.href = '/logout'；
          waterMark.set('')//清除水印
          this.$router.push({name: 'login'})
        } else if (type === 'userInfo') {
          // todo 添加路由
          let path = '/sys/user/userInfo'
          let editMyInfo = {route: path, title: '个人信息', url: path, isHome: false, isLock: false}
          _this.tabs[path] = editMyInfo
          if (path !== _this.tabCheck) {
            _this.tabCheck = path
          }
        } else if (type === 'password') {
          //修改密码窗口
          this.dialogPasswordVisible = true
        }
      },
      //tab更多操作
      tabCommand: function (type) {
        let _this = this
        let lockTabs = this.$t.getLocalStorageItem('lockTabs') || {}
        //关闭其他
        if (type === 'closeOther') {
          for (let key in _this.tabs) {
            if (key !== _this.tabCheck && key !== '/home' && lockTabs[key] === undefined) {
              _this.$delete(_this.tabs, key)
            }
          }
        } else if (type === 'closeAll') {
          for (let key in _this.tabs) {
            if (key !== '/home' && lockTabs[key] === undefined) {
              _this.$delete(_this.tabs, key)
            }
          }
          _this.tabCheck = '/home'
          _this.$router.push({path: '/home'})
        }
      },
      //刷新当前页面
      refresh: function () {
        this.tabCheck = this.cmObj.route
        // this.$router.push({path:"/redirect"+this.cmObj.route});
        this.showCM = false

        this.$nextTick(() => {
          this.$router.replace({
            path: '/redirect' + this.cmObj.route
          })
        })
      }
      //锁定/解锁当前页面
      , isLock: function (isLock) {
        this.showCM = false
        this.tabs[this.cmObj.route].isLock = !isLock
        let lockTabs = this.$t.getLocalStorageItem('lockTabs') || {}
        //tabs本地缓存操作
        if (!isLock) {
          lockTabs[this.cmObj.route] = this.cmObj
        } else {
          this.$delete(lockTabs, this.cmObj.route)
        }
        this.$t.setLocalStorageItem('lockTabs', lockTabs)
      }
      //关闭其他
      , closeOther: function () {
        let _this = this
        let lockTabs = this.$t.getLocalStorageItem('lockTabs') || {}
        for (let key in _this.tabs) {
          if (key !== _this.cmObj.route && key !== '/home' && lockTabs[key] === undefined) {
            _this.$delete(_this.tabs, key)
          }
        }
        _this.tabCheck = _this.cmObj.route
      }
      //关闭所有
      , closeAll: function () {
        let _this = this
        let lockTabs = this.$t.getLocalStorageItem('lockTabs') || {}
        for (let key in _this.tabs) {
          if (key !== '/home' && lockTabs[key] === undefined) {
            _this.$delete(_this.tabs, key)
          }
        }
        _this.tabCheck = '/home'
        _this.$router.push({path: '/home'})
      },
      //tab滚轮监听
      handleTabWheel: function (e) {
        let scrollBodyWidth = document.getElementsByClassName('scroll-body')[0].offsetWidth
        let scrollOuterWidth = document.getElementsByClassName('scroll-outer')[0].offsetWidth
        if (scrollBodyWidth < scrollOuterWidth) {
          return
        }
        let wheelDelta = e.wheelDelta
        let tabLeftPX = this.tabLeft.left.replace('px', '')
        let resPX = parseInt(tabLeftPX)
        if (resPX + wheelDelta > 0) {
          this.tabLeft = {left: '0px'}
          return
        } else if (resPX + scrollBodyWidth + wheelDelta <= scrollOuterWidth) {
          this.tabLeft = {left: scrollOuterWidth - scrollBodyWidth - 10 + 'px'}
          return
        }
        if (scrollBodyWidth > scrollOuterWidth) {
          this.tabLeft = {left: resPX + wheelDelta + 'px'}
        }
      },
      //刷新缓存
      handleRefreshCache: function () {
        localStorage.clear()
        let _this = this
        setTimeout(function () {
          _this.$notify({
            title: '成功',
            message: '缓存刷新完毕',
            offset: 100,
            type: 'success'
          })
        }, 500)
      },
      handleFullScreen: function () {
        let fullScreen = this.fullScreen
        if (!this.fullScreen) {
          let el = document.documentElement
          let rfs = el.requestFullScreen || el.webkitRequestFullScreen ||
            el.mozRequestFullScreen || el.msRequestFullScreen
          if (rfs) { //typeof rfs != "undefined" && rfs
            rfs.call(el)
          } else if (typeof window.ActiveXObject != 'undefined') {
            //for IE，这里其实就是模拟了按下键盘的F11，使浏览器全屏
            let wscript = new ActiveXObject('WScript.Shell')
            if (wscript != null) {
              wscript.SendKeys('{F11}')
            }
          }
        } else {
          let el = document
          let cfs = el.cancelFullScreen || el.webkitCancelFullScreen ||
            el.mozCancelFullScreen || el.exitFullScreen
          if (cfs) { //typeof cfs != "undefined" && cfs
            cfs.call(el)
          } else if (typeof window.ActiveXObject != 'undefined') {
            //for IE，这里和fullScreen相同，模拟按下F11键退出全屏
            let wscript = new ActiveXObject('WScript.Shell')
            if (wscript != null) {
              wscript.SendKeys('{F11}')
            }
          }
        }
        this.fullScreen = !fullScreen
      },
      //获取面包屑导航
      getBreadcrumb: function () {
        this.breadcrumbs = this.$route.matched.filter(item =>
          item.meta && item.meta.title && item.meta.breadcrumb !== false
        )
      }
    }
  }
</script>
